<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>jszip的使用</title>
    <style>
        #app {
            padding: 20px;
        }

        img {
            width: 200px;
        }

        .file-container {
            padding: 10px;
        }

        .file-container .file-item {
            border: 1px solid #ccc;
        }

        .file-container .file-item .title {
            color: #666;
            font-size: 16px;
            font-weight: bold;
        }

        .file-container .file-item .content {
            color: #666;
            font-size: 14px;
        }
    </style>
</head>

<body>
    <div id="app">
        <div>
            <h1>解压</h1>
            <input type="file" accept=".zip" @change="handleClick" />
            <div>
                <h2>解压后的文件</h2>
                <div class="file-container">
                    <div class="file-item" v-for="(item, index) in dataList" :key="index">
                        <p class="title">{{item.fileName}}</p>
                        <div class="content">
                            <img v-if="item.type === 'img'" :src="item.content" alt="">
                            <p v-if="item.type === 'text'">{{item.content}}</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <hr>
        <div>
            <h1>加压</h1>
            <button @click="exportZip">导出</button><br>
            <img v-for="(item, index) in imgList" :src="item" alt="">
        </div>
    </div>
    <script src="./node_modules/vue/dist/vue.min.js"></script>
    <script src="./node_modules/jszip/dist/jszip.min.js"></script>
    <script src="./node_modules/file-saver/dist/FileSaver.min.js"></script>
    <script>
        new Vue({
            el: '#app',
            data: {
                dataList: [],
                imgList: [
                    './static/安卓壁纸_55517a9169401b1e88b13734.jpg',
                    './static/安卓壁纸_55517a9269401b1e88b13735.jpg',
                    './static/安卓壁纸_55517aab69401b1e88b13739.jpg',
                    './static/安卓壁纸_55517ab069401b1e88b1373a.jpg',
                    './static/安卓壁纸_55517ab569401b1e88b1373b.jpg'
                ]
            },
            methods: {
                handleClick(e) {
                    const zipFile = e.target.files[0]
                    const jszip = new JSZip()
                    this.dataList.length = 0
                    jszip.loadAsync(zipFile).then((zip) => { // 读取zip
                        for (let key in zip.files) { // 判断是否是目录
                            if (!zip.files[key].dir) {
                                if (/\.(png|jpg|jpeg|gif)$/.test(zip.files[key].name)) { // 判断是否是图片格式
                                    let base = zip.file(zip.files[key].name).async(
                                        'base64') // 将图片转化为base64格式
                                    base.then(res => {
                                        this.dataList.push({
                                            fileName: zip.files[key].name,
                                            type: 'img',
                                            content: `data:image/png;base64,${res}`
                                        })
                                    })
                                }
                                if (/\.(txt)$/.test(zip.files[key].name)) { // 判断是否是文本文件
                                    let base = zip.file(zip.files[key].name).async(
                                        'string') // 以字符串形式输出文本内容
                                    base.then(res => {
                                        this.dataList.push({
                                            fileName: zip.files[key].name,
                                            type: 'text',
                                            content: res
                                        })
                                    })
                                }
                            }
                        }
                    })
                },
                async exportZip() {
                    const imgList = this.imgList
                    const proList = []
                    const zip = new JSZip()
                    const cache = {}
                    await imgList.forEach(item => {
                        const pro = this.getUrlBase64(item, '.jpg').then(base64 => {
                            const fileName = item.replace(/(.*\/)*([^.]+)/i,"$2")
                            zip.file(fileName, base64.substring(base64.indexOf(',') + 1), {
                                base64: true
                            })
                            cache[fileName] = base64
                        })
                        proList.push(pro)
                    })
                    Promise.all(proList).then(res => {
                        zip.generateAsync({
                            type: 'blob'
                        }).then(content => { // 生成二进制流
                            saveAs(content, 'images.zip') // 利用file-saver保存文件
                        })
                    })
                },
                /**
                 *
                 * @param url 图片路径
                 * @param ext 图片格式
                 * @param callback 结果回调
                 */
                async getUrlBase64(url, ext) {
                    return new Promise((resolve, reject) => {
                        var canvas = document.createElement('canvas') // 创建canvas DOM元素
                        var ctx = canvas.getContext('2d')
                        var img = new Image()
                        img.crossOrigin = 'Anonymous' // 处理跨域
                        img.src = url
                        img.onload = () => {
                            canvas.width = img.width // 指定画板的高度,自定义
                            canvas.height = img.height // 指定画板的宽度，自定义
                            ctx.drawImage(img, 0, 0) // 参数可自定义
                            var dataURL = canvas.toDataURL('image/' + ext)
                            resolve(dataURL) // 回调函数获取Base64编码
                            canvas = null
                        }
                    })
                }
            }
        })
    </script>
</body>

</html>